package com.lv.common.widget.textview;

/**
 * 作者： ygx
 * 创建日期：2023/8/10 9:40 AM
 * 签名： 天行健，君子以自强不息；地势坤，君子以厚德载物。
 * -    _              _           _     _   ____  _             _ _
 * -   / \   _ __   __| |_ __ ___ (_) __| | / ___|| |_ _   _  __| (_) ___
 * -  / _ \ | '_ \ / _` | '__/ _ \| |/ _` | \___ \| __| | | |/ _` | |/ _ \
 * - / ___ \| | | | (_| | | | (_) | | (_| |  ___) | |_| |_| | (_| | | (_) |
 * -/_/   \_\_| |_|\__,_|_|  \___/|_|\__,_| |____/ \__|\__,_|\__,_|_|\___/
 * <p>
 * You never know what you can do until you try !
 * ----------------------------------------------------------------
 * 描述：
 */

import android.graphics.Canvas;
import android.graphics.LinearGradient;
import android.graphics.Paint;
import android.graphics.Shader;
import android.text.style.ReplacementSpan;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

public  class GradientFontSpan extends ReplacementSpan {
    private int mSize;
    private int mStartColor;
    private int mEndColor;

    public GradientFontSpan(int startColor, int endColor) {
        mStartColor = startColor;
        mEndColor = endColor;
    }

//        public GradientFontSpan(Context context) {
//            mStartColor = Color.parseColor("#FF9600");
//            mEndColor = Color.parseColor("#7D4300");
//        }

    @Override
    public int getSize(@NonNull Paint paint, CharSequence text, int start, int end,
                       @Nullable Paint.FontMetricsInt fm) {
        mSize = Math.round(paint.measureText(text, start, end));
        Paint.FontMetricsInt metrics = paint.getFontMetricsInt();
        if (fm != null) {
            fm.top = metrics.top;
            fm.ascent = metrics.ascent;
            fm.descent = metrics.descent;
            fm.bottom = metrics.bottom;
        }
        return mSize;
    }

    @Override
    public void draw(@NonNull Canvas canvas, CharSequence text, int start, int end, float x,
                     int top, int y, int bottom, @NonNull Paint paint) {
        LinearGradient gradient = new LinearGradient(0, 0, mSize, 0, mStartColor, mEndColor,
                Shader.TileMode.CLAMP);
        paint.setShader(gradient);
        canvas.drawText(text, start, end, x, y, paint);
    }
}
